﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using NHADAT.Authentication;

namespace NHADAT.AdminCP
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // if user logined
            if (User.Identity.IsAuthenticated)
            {
                Response.Redirect("Default.aspx");
            }
        }

        protected void ShowToastr(System.Web.UI.Page page, string message, string title, string type = "info")
        {
            page.ClientScript.RegisterStartupScript(page.GetType(), "toastr_message",
                  String.Format("toastr.{0}('{1}', '{2}');", type.ToLower(), message, title), addScriptTags: true);
        }

        protected bool CheckLoginInfo(string username, string password)
        {
            if (username == "admin" && password == "admin")
                return true;
            return false;
        }

        protected void btnDangNhap_Click(object sender, EventArgs e)
        {
            if (txtUsername.Text.Trim() == "" || txtPassword.Text.Trim() == "")
            {
                ShowToastr(this.Page, "Chưa nhập đầy đủ tên đăng nhập và mật khẩu!", "", "warning");
                return;
            }

            if (!CheckLoginInfo(txtUsername.Text.Trim(), txtPassword.Text.Trim()))
                ShowToastr(this.Page, "Tên đăng nhập hoặc mật khẩu không đúng!", "", "error");
            else
            {
                ShowToastr(this.Page, "Đăng nhập thành công!", "", "success");
                SetAdminLoginSession(113, chkRemember.Checked);
            }
        }

        protected void SetAdminLoginSession(int UserId, bool isRememberMe)
        {            
            try
            {
                var adminSession = new UserLoginSession()
                {
                    UserId = UserId,
                    UserLoginType = "Admin"
                };

                // Create the cookie that contains the forms authentication ticket
                HttpCookie authCookie = FormsAuthentication.GetAuthCookie(adminSession.UserId.ToString(), isRememberMe);
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

                //var newTicket = new FormsAuthenticationTicket(ticket.Version, adminSession.UserId.ToString(), ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, adminSession.UserLoginType, ticket.CookiePath);
                
                string data = UserLoginSession.SerializeToBase64String(adminSession);
                var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, data, ticket.CookiePath);
                
                
                authCookie.Value = FormsAuthentication.Encrypt(newTicket);
                // Manually add the authCookie to the Cookies collection
                Response.Cookies.Add(authCookie);

                string returnUrl = Request.QueryString["ReturnUrl"];
                if (returnUrl == null) returnUrl = "/";

                // Don't call FormsAuthentication.RedirectFromLoginPage since it
                // could
                // replace the authentication ticket (cookie) we just added
                Response.Redirect(returnUrl);
            }
            catch
            {
            }
        }
        
    }
}